package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;
    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1. 设置前面5天的时间
        Date date = DateTime.now().minusDays(5).toDate();

        //2. 查询前面5天的所有的文章数据
        List<ApArticle> articleList = apArticleMapper.findArticleListByDays(date);

        if(null != articleList && articleList.size() > 0){
            //3. 计算所有的文章的得分
            List<HotArticleVo> voList = computeHotArticleScore(articleList);
            //4. 把文章缓存到redis(每个频道都要缓存， 推荐需要缓存)
            cacheTagtoRedis(voList);
        }


    }

    /**
     * 缓存所有的数据到redis
     * 每个频道都要缓存， 推荐需要缓存
     * @param voList
     */
    private void cacheTagtoRedis(List<HotArticleVo> voList) {
        ResponseResult reponse = wemediaClient.getChannels();
        if(reponse.getCode().equals(200)){
            String json = JSON.toJSONString(reponse.getData());
            List<WmChannel> channelList = JSON.parseArray(json, WmChannel.class);

            for (WmChannel wmChannel : channelList) {
                //找到遍历出来的频道的所有的文章
                List<HotArticleVo> list = voList.stream()
                        .filter(vo -> {
                            if(vo.getChannelId() != null){
                                return vo.getChannelId().equals(wmChannel.getId());
                            }else{
                                return false;
                            }
                        })
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .limit(30)
                        .collect(Collectors.toList());

                //把当前频道的文章内容缓存到redis
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId(), JSON.toJSONString(list));
            }
        }

        //缓存推荐的数据
        List<HotArticleVo> list = voList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG, JSON.toJSONString(list));
    }

    /**
     * 计算文章的的得分数据
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> articleList) {
        List<HotArticleVo> voList = new ArrayList<>(articleList.size());

        for (ApArticle article : articleList) {
            HotArticleVo vo = new HotArticleVo();
            BeanUtils.copyProperties(article, vo);

            vo.setScore(computeScore(article));

            voList.add(vo);
        }

        return voList;
    }

    private Integer computeScore(ApArticle apArticle) {
        int score = 0;

        if(apArticle.getLikes() != null){
            score += apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }

        if(apArticle.getComment() != null){
            score += apArticle.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(apArticle.getCollection() != null){
            score += apArticle.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }


        return score;
    }
}
